package com.hjs.juc;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * 原子变量;jdk1.5之后，java.util.concurrnet.atomic提供了常用的原子变量
 * 1.都是使用volatile修饰
 * 2.使用CAS（Compare-And-Swap）算法保证原子性
 *      1>.CAS是硬件对于并发操作共享数据的支持
 *      2>.三个操作数:内存值V 预估值A 更新值B
 *          当且仅当 V == A,才会 V == B
 *
 *
 * @author hanjinsong
 * @date 2020-02-19 10:40
 */
public class TestAtomic {

    public static void main(String[] args) {
        ThreadAtomic threadAtomic = new ThreadAtomic();
        for (int i = 0; i < 10; i++) {
            new Thread(threadAtomic).start();
        }
    }

}
class ThreadAtomic implements Runnable {

//    private int num = 0;
    private AtomicInteger anum = new AtomicInteger();

    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName()+" : "+getAddNum());
    }

    public int getAddNum(){
//        return num++;
        return anum.getAndIncrement();
    }
}
